package com.hqyj.javaGraduation.config;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/payServer")
@Component
public class PaySocketServer {

    //初始化方法
    @PostConstruct
    public void init() {
        System.out.println("支付宝 推送 消息websocket 加载");
    }

    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        SessionSet.add(session);
        System.out.println("用户" + session.getId() + "连接成功");

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SessionSet.remove(session);
        System.out.println("用户" + session.getId() + "已经下线");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("用户" + session.getId() + "发送的信息:" + message);

    }

    @OnError
    public void onError(Session s, Throwable e){
        System.out.println(s.getId()+"连接错误");
    }

    //发送信息
    public static void sendMessage(String message){

        //遍历所有的客户端
        Iterator<Session> iterable = SessionSet.iterator();
        while(iterable.hasNext()){
            Session s = iterable.next();
            if(s.isOpen()){
                try {
                    s.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
